var arrImg=[
  {
    "name":"car",
    "url":"images/img_car.png"
  },
  {
    "name":"bg",
    "url":"images/bg_game.png"
  }
];
var ImgJson={};
var gameReady=false;
function loadImage(arrImg){
  var n=0;
  for(var i=0;i<arrImg.length;i++){
    (function(i){
      var image=new Image();
      image.src=arrImg[i].url;
      image.onload=function(){ 
        n++;
        ImgJson[arrImg[i].name]=image;
        if(n==arrImg.length){
          gameReady=true;
        }
      }
    })(i)
  }
}
loadImage(arrImg);

var canvas=$(".canvas")[0];
var gd=canvas.getContext("2d");
var winH=$(window).height();
var winW=$(window).width();

var startDate=null;
var endDate=null;
var timer2=null;
var energyH=$(".Energy_max").height();
var per=null;
var last_dur=1;
canvas.width=winW;
canvas.height=winH;

var car_pos=0.66*winH
var bg_pos=-1.8*winH
var state=1;

var car={
  "w":0.097*winH,
  "h":0.204*winH,
  "x":winW/2-0.097*winH/2,
  "y":winH,
  "rh":247,
  "ry":0
}
var bg={
  "w":0.621*winH,
  "h":2.8*winH,
  "x":winW/2-0.621*winH/2,
  "y":-2.8*winH+winH
  // "y":0
}

function DrawStartbg(fn){
    if(fn){
      fn();
    }
    gd.drawImage(
      ImgJson.bg,bg.x,bg.y,bg.w,bg.h
    );
}

function DrawCar(fn){
    if(fn){
      fn();
    }
    gd.drawImage(
      ImgJson.car,0,car.ry,118,car.rh,car.x,car.y,car.w,car.h
    );
}

setInterval(function(){
  if(gameReady){
    if(state==1){
        DrawStartbg()
        DrawCar(function(){
          car.y*=0.994;
          if(car.y<0.66*winH){
            car.y=0.66*winH
            state=6;
          }
        })
    }
    if(state==2){
        DrawStartbg(function(){
          bg.y+=v;
          v-=a;
          console.log(bg.y)
          if(v<=0||bg.y>=0){
            state=3;
          }
        })
        DrawCar()
    }
    if(state==3){
        DrawStartbg()
        DrawCar(function(){
          car.y-=v;
          v-=a;
          if(car.y<=0.502*winH){
            state=4
          }
          if(v<=0){
            state=5
            if(per<0.8/3){
              console.log(1)
              json["a1"].play();
            }
            if(per<0.8/3*2&&per>0.8/3){
              console.log(1)
              json["a2"].play();
            }
            if(per>0.8/3*2&&per<0.8){
              console.log(1)
              json["a3"].play();
            }

            $(".popup_gameOver").show();
            $(".gameOver_state1").show();
            $(".gameOver_p2 .yellow").html(Math.round(per/0.8*520*100)/100)
          }
        })
    }
    if(state==4){
        DrawStartbg()
        DrawCar(function(){
          car.h-=v;
          v-=a;
          car.rh-=375/winW*v*2;
          car.ry+=375/winW*v*2;
          if(car.h<=0){
            car.h=0;
            state=5;
            $(".gameOver_state2").show();
            $(".popup_gameOver").show();
          }
        })
    }
  }
},Math.round(1000/120))

//part1
//汽车进入

//part2
//按充能键车辆运行

//part3
//根据车辆状态做出不同动作

var s=null;
var v=null;
var t=null;
var a=0.1;


$(".button_charge").on("touchstart",function(){
  $(".button_charge2").show();
  startDate=new Date();
  charge();
})

$(".button_charge").on("touchend",function(){
  $(".button_charge2").hide();
  clearInterval(timer2)
  state=2;
  var cc=per;
  if(per>0.8){
    cc=1;
  }
  s=1.8*winH*cc/0.8;
  v=Math.sqrt(s*a*2);
  t=v/a;
  $(".button_charge").unbind("touchstart")
})

function charge(){
  timer2=setInterval(function(){
    endDate=new Date();
    per=(endDate-startDate)/3000;
    if(per<1){
      $(".Energy_max").css({
        "height":energyH*per
      })
    }
  },20)
}

var json={};
var audio=[
  "video/lose.mp3",
  "video/1p1.mp3",
  "video/1p2.mp3",
  "video/1p3.mp3"
];


for(var i=0;i<4;i++){

  console.log(audio[i])
  musicLoad($(".bgmusic")[i],audio[i],i);
}

function musicLoad(obj,src1,i){
        function log(info) {
            // alert(info);
        }
        function forceSafariPlayAudio() {
            audioEl.load(); // iOS 9   还需要额外的 load 一下, 否则直接 play 无效
            audioEl.play(); // iOS 7/8 仅需要 play 一下
        }
        var start=null;
        var end=null;
        var audioEl = obj;
        // 可以自动播放时正确的事件顺序是
        // loadstart
        // loadedmetadata
        // loadeddata
        // canplay
        // play
        // playing
        //
        // 不能自动播放时触发的事件是
        // iPhone5  iOS 7.0.6 loadstart
        // iPhone6s iOS 9.1   loadstart -> loadedmetadata -> loadeddata -> canplay

        audioEl.src = src1;
        audioEl.addEventListener('loadstart', function() {
           start = new Date().getTime();
            log('loadstart');
        }, false);
        audioEl.addEventListener('loadeddata', function() {
            log('loadeddata');
        }, false);
        audioEl.addEventListener('loadedmetadata', function() {
            log('loadedmetadata');
        }, false);
        audioEl.addEventListener('canplay', function() {
          end = new Date().getTime();
          // alert(1)
          // audioEl.play(); 
          json["a"+i]=audioEl;
          log('canplay');
        }, false);
        audioEl.addEventListener('play', function() {
            log('play');
            // 当 audio 能够播放后, 移除这个事件
            // window.removeEventListener('touchstart', forceSafariPlayAudio, false);
        }, false);
        audioEl.addEventListener('playing', function() {
            log('playing');
        }, false);
        audioEl.addEventListener('pause', function() {
            log('pause');
        }, false);

        // 由于 iOS Safari 限制不允许 audio autoplay, 必须用户主动交互(例如 click)后才能播放 audio,
        // 因此我们通过一个用户交互事件来主动 play 一下 audio.
        // window.addEventListener('touchstart', forceSafariPlayAudio, false);
}